package com.yc.cloud.openai.portal.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.cloud.common.basic.dto.BaseQueryParam;
import com.yc.cloud.common.oss.service.OssFileService;
import com.yc.cloud.openai.entity.ImageRecord;
import com.yc.cloud.openai.mapper.ImageRecordMapper;
import com.yc.cloud.openai.portal.dto.request.ImageRecordListParam;
import com.yc.cloud.openai.portal.service.ImageRecordService;
import com.yc.cloud.openai.vo.ImageRecordVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.val;

/**
 * <p>
 * AI绘画记录 服务实现类
 * </p>
 *
 * @author Yancy
 * @since 2024-10-30
 */
@Service
public class ImageRecordServiceImpl extends ServiceImpl<ImageRecordMapper, ImageRecord> implements ImageRecordService {

    private final OssFileService ossFileService;

    public ImageRecordServiceImpl(OssFileService ossFileService) {
        this.ossFileService = ossFileService;
    }

    @Override
    public IPage<ImageRecordVo> list(ImageRecordListParam param, BaseQueryParam queryParam) {
        val query = new QueryWrapper<ImageRecord>();
        // 增加过滤条件,查询当前客户端相关信息
        val clientIds = StrUtil.split(param.getClientId(), ",");
        if (clientIds.size() == 1) {
            query.eq(ImageRecord.CLIENT_ID, clientIds.get(0));
        } else {
            query.in(ImageRecord.CLIENT_ID, clientIds);
        }
        // 增加任务状态过滤条件
        if (CollUtil.isNotEmpty(param.getStatusList())) {
            query.in(ImageRecord.STATUS, param.getStatusList());
        }
        IPage<ImageRecord> page;
        // 排序
        if (StrUtil.isNotEmpty(queryParam.getSortBy())) {
            if (BaseQueryParam.ORDER_DESC.equals(queryParam.getOrder())) {
                query.orderByDesc(queryParam.getSortBy());
            } else if (BaseQueryParam.ORDER_ASC.equals(queryParam.getOrder())) {
                query.orderByAsc(queryParam.getSortBy());
            }
        }
        // 模糊查询
        if (StrUtil.isNotEmpty(queryParam.getKeyword())) {
            query.and(queryWrapper -> {
                queryWrapper.like(ImageRecord.PROMPT, queryParam.getKeyword());
            });
        }
        // 分页
        if (queryParam.getPage()) {
            page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize(), true);
        } else {
            page = new Page<>(queryParam.getPageNum(), baseMapper.selectCount(query), true);
        }
        val result = baseMapper.selectPage(page, query);
        return result.convert(this::convertVo);
    }

    @Override
    public ImageRecord create(ImageRecord param) {
        val imagerecord = new ImageRecord();
        BeanUtils.copyProperties(param, imagerecord);
        val saveFlag = save(imagerecord);
        return saveFlag ? imagerecord : null;
    }

    @Override
    public ImageRecord get(Long id) {
        return getById(id);
    }

    @Override
    public boolean delete(Long id) {
        return removeById(id);
    }

    @Override
    public List<ImageRecord> listByStatus(List<String> statusList) {
        val query = new QueryWrapper<ImageRecord>();
        if (CollUtil.isNotEmpty(statusList)) {
            query.in(ImageRecord.STATUS, statusList);
        }
        return baseMapper.selectList(query);

    }

    @Override
    public void updateStatusByUuid(String uuid, String status) {
        LambdaUpdateWrapper<ImageRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ImageRecord::getUuid, uuid)
                .set(ImageRecord::getStatus, status);
        // 执行更新操作
        this.update(updateWrapper);
    }

    @Override
    public ImageRecord update(Long id, ImageRecord param) {
        val imagerecord = new ImageRecord();
        BeanUtils.copyProperties(param, imagerecord);
        imagerecord.setId(id);
        val updateFlag = updateById(imagerecord);
        return updateFlag ? imagerecord : null;
    }

    @Override
    public ImageRecordVo convertVo(ImageRecord imagerecord) {
        if (imagerecord == null) {
            return null;
        }
        val vo = new ImageRecordVo();
        BeanUtils.copyProperties(imagerecord, vo);
        // 同时去查询此次任务生成的图片
        val ossFileList = ossFileService.listByParentFileId(imagerecord.getUuid());
        // 转换成VO对象
        vo.setImages(ossFileService.convertVo(ossFileList));
        return vo;
    }

    @Override
    public List<ImageRecordVo> convertVo(List<ImageRecord> ImageRecordList) {
        if (CollUtil.isNotEmpty(ImageRecordList)) {
            return ImageRecordList.stream().map(this::convertVo).collect(Collectors.toList());
        }
        return new ArrayList<>();
    }
}
